const express = require('express')
const router = express.Router()
const Entrepreneur = require('../models/Entrepreneur')
const { markFileAsReferenced, unmarkFileReference } = require('../middlewares/fileReference')
const authMiddleware = require('../middlewares/auth')
// 创建企业家信息记录
router.post('/addEntrepreneur', authMiddleware(), async (req, res) => {
  try {
    const { joinDate, fileId, name, company, position, industry, business, connections, resources, projects } = req.body

    // 验证日期格式
    if (!/^\d{4}-\d{2}-\d{2}$/.test(joinDate)) {
      return res.status(400).json({ message: '日期格式应为YYYY-MM-DD' })
    }

    // 验证必要字段
    const requiredFields = ['name', 'company', 'position', 'industry', 'business']
    const missingFields = requiredFields.filter(field => !req.body[field])
    if (missingFields.length > 0) {
      return res.status(400).json({
        message: `缺少必填字段：${missingFields.join(', ')}`
      })
    }

    const newEntrepreneur = new Entrepreneur({
      joinDate,
      files: fileId,
      name,
      company,
      position,
      industry,
      business,
      connections,
      resources,
      projects
    })

    const savedEntrepreneur = await newEntrepreneur.save()
    await markFileAsReferenced(fileId)

    res.status(201).json({
      data: savedEntrepreneur,
      message: '创建成功'
    })
  } catch (err) {
    res.status(400).json({ message: err.message })
  }
})

// 查询企业家信息记录
router.get('/queryEntrepreneur', async (req, res) => {
  try {
    const { name, entrepreneurId, year, pageNum = 1, pageSize = 10 } = req.query
    const filter = {}
    const options = {
      skip: (pageNum - 1) * pageSize,
      limit: parseInt(pageSize),
      sort: { joinDate: -1 }
    }

    if (entrepreneurId) filter._id = entrepreneurId
    if (name) filter.name = { $regex: name, $options: 'i' }
    // 添加年份筛选
    if (year) {
      // 根据joinDate筛选年份
      const startDate = new Date(`${year}-01-01`)
      const endDate = new Date(`${year}-12-31`) 
      filter.joinDate = {
        $gte: startDate,
        $lte: endDate
      }
    }
    const [entrepreneurs, total] = await Promise.all([
      Entrepreneur.find(filter).populate('files').skip(options.skip).limit(options.limit).sort(options.sort),
      Entrepreneur.countDocuments(filter)
    ])

    res.json({
      data: entrepreneurs,
      pageNum: parseInt(pageNum),
      pageSize: parseInt(pageSize),
      totalPages: Math.ceil(total / options.limit),
      total,
      message: '查询成功'
    })
  } catch (err) {
    res.status(500).json({ message: err.message })
  }
})

// 更新企业家信息记录
router.post('/updateEntrepreneur', authMiddleware(), async (req, res) => {
  try {
    const { entrepreneurId, joinDate, fileId, name, company, position, industry, business, connections, resources, projects } = req.body

    const entrepreneur = await Entrepreneur.findById(entrepreneurId)
    if (!entrepreneur) return res.status(404).json({ message: '记录不存在' })

    // 处理文件更新
    if (fileId && fileId !== entrepreneur.files.toString()) {
      await unmarkFileReference(entrepreneur.files)
      await markFileAsReferenced(fileId)
      entrepreneur.files = fileId
    }

    Object.assign(entrepreneur, {
      joinDate,
      name,
      company,
      position,
      industry,
      business,
      connections,
      resources,
      projects
    })
    const updatedEntrepreneur = await entrepreneur.save()

    res.json({
      data: updatedEntrepreneur,
      message: '更新成功'
    })
  } catch (err) {
    res.status(400).json({ message: err.message })
  }
})

// 删除企业家信息记录
router.post('/deleteEntrepreneur', authMiddleware(), async (req, res) => {
  try {
    const entrepreneur = await Entrepreneur.findByIdAndDelete(req.body.entrepreneurId)
    if (!entrepreneur) return res.status(404).json({ message: '记录不存在' })

    await unmarkFileReference(entrepreneur.files)

    res.json({ message: '删除成功' })
  } catch (err) {
    res.status(500).json({ message: err.message })
  }
})

module.exports = router
